<?php
namespace Api;
use Api\Autoloader\Exception\ClassNotFoundException;

/**
 * Class Autoloader
 * @package Api
 * @author Steffen Brem <steffenbrem@gmail.com>
 */
class Autoloader
{
    protected $namespaces = array();

    /**
     * Constructor
     */
    public function __construct()
    {
        spl_autoload_register(array($this, "load"));
    }

    /**
     * @param $namespace
     * @param $path
     */
    public function register($namespace, $path)
    {
        $this->namespaces[$namespace] = $path;
    }

    /**
     * @param $class
     * @throws Autoloader\Exception\ClassNotFoundException
     */
    public function load($class)
    {
        $path       = explode('\\', $class);
        $namespace  = array_shift($path);
        $filename   = array_pop($path);

        $clean_path = (($path) ? strtolower(implode(DIRECTORY_SEPARATOR, $path)) . DIRECTORY_SEPARATOR : '') . $filename . '.php';

        if (file_exists($clean_path))
        {
            require_once $clean_path;
            return;
        }
        else
        {
            foreach ($this->namespaces as $_ns => $_path)
            {
                if ($_ns == $namespace)
                {
                    $file = rtrim($_path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $clean_path;

                    if (file_exists($file))
                    {
                        require_once $file;
                        return;
                    }
                }
            }
        }

        throw new ClassNotFoundException('Class ' . $class . ' could not be found.');
    }
}